import sys
import os
import time
import logging
from datetime import datetime

# 添加项目根目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(current_dir)
sys.path.insert(0, project_root)

from config.config import Config
from utils.NeuroPy3 import NeuroPy
from utils.NotchFilter import NotchFilter
from utils.EOGArtifactRemover import EOGArtifactRemover
from utils.EMGArtifactRemover import EMGArtifactRemover
from response.BrainWaveResult import BrainWaveResult
from service.DeltaService import DeltaService
from service.WaveletDeltaService import WaveletDeltaService
from service.ThetaService import ThetaService
from service.FrequencyBandService import FrequencyBandService
from service.AdvancedSignalFilter import AdvancedSignalFilter
from exception.base_exceptions import (
    DeviceConnectionException, DeviceDataException, SignalProcessingException,
    FilterException, BrainStateException
)
from exception.exception_handler import global_exception_handler

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class WaveService:
    """
    脑电波服务类 - 8频域集成版本
    
    数据处理流水线（支持8频域分析）：
    1. 获取8频域原始数据 -> BrainWaveResult (Delta, Theta, Low Alpha, High Alpha, Low Beta, High Beta, Low Gamma, Mid Gamma)
    2. 陷波滤波器 (可选) -> BrainWaveResult  
    3. EOG伪迹去除 (可选) -> BrainWaveResult
    4. EMG伪迹去除 (可选) -> BrainWaveResult
    5. Delta服务 (可选) -> BrainWaveResult
    6. Theta服务 (可选) -> BrainWaveResult
    7. 高级信号滤波 (可选) -> BrainWaveResult
    8. 频段优化服务 (可选) -> BrainWaveResult
    
    每个过滤器都接收和返回8频域BrainWaveResult格式
    支持更精细的脑状态分析：深睡、浅睡、REM、入睡、专注、放松、困倦等
    """
    
    def __init__(self, port=None, enable_notch_filter=True, enable_eog_removal=True,
                 enable_emg_removal=True, use_delta_service=False, enable_theta_optimization=True, 
                 enable_advanced_filter=True, enable_band_optimization=True, analysis_duration=10):
        """
        初始化服务
        
        Args:
            port: 串口地址
            enable_notch_filter: 是否启用陷波滤波器
            enable_eog_removal: 是否启用EOG伪迹去除
            enable_emg_removal: 是否启用EMG伪迹去除
            use_delta_service: 是否使用Delta服务 (False=标准, True=小波包)
            enable_theta_optimization: 是否启用Theta优化
            enable_advanced_filter: 是否启用高级信号滤波器
            enable_band_optimization: 是否启用频段优化
            analysis_duration: 分析时长(秒)，默认10秒，可动态设置
        """
        self.port = port or Config.DEVICE_PORT
        self.neuropy = None
        self.analysis_duration = analysis_duration  # 动态分析时长
        
        # 过滤器开关
        self.enable_notch_filter = enable_notch_filter
        self.enable_eog_removal = enable_eog_removal
        self.enable_emg_removal = enable_emg_removal
        self.use_delta_service = use_delta_service
        self.enable_theta_optimization = enable_theta_optimization
        self.enable_advanced_filter = enable_advanced_filter
        self.enable_band_optimization = enable_band_optimization
        
        # 原始时域信号缓冲区（用于正确的陷波滤波处理）
        from collections import deque
        self.raw_signal_buffer = deque(maxlen=256)  # 保存最近256个原始信号样本（0.5秒数据）
        
        # 初始化过滤器
        self._init_filters()
        
    def _init_filters(self):
        """初始化各个过滤器"""
        # 1. 陷波滤波器 (50Hz工频干扰)
        if self.enable_notch_filter:
            self.notch_filter = NotchFilter(
                sampling_rate=512.0,
                notch_freq=50.0,
                quality_factor=30.0
            )
            logger.info("陷波滤波器已启用 - 50Hz")
        else:
            self.notch_filter = None
        
        # 2. EOG伪迹去除器
        if self.enable_eog_removal:
            self.eog_remover = EOGArtifactRemover(
                blink_threshold=50.0,  # 降低阈值从100.0到50.0
                window_size=50,
                ica_components=4,
                sampling_rate=512.0
            )
            logger.info("EOG伪迹去除器已启用 - 阈值:50.0")
        else:
            self.eog_remover = None
            
        # 3. EMG伪迹去除器
        if self.enable_emg_removal:
            self.emg_remover = EMGArtifactRemover(
                sampling_rate=512,
                window_size=100,
                emg_threshold=0.3,  # 降低阈值从0.6到0.3
                wavelet='db4',
                decomp_levels=6
            )
            logger.info("EMG伪迹去除器已启用 - 阈值:0.3")
        else:
            self.emg_remover = None
            
        # 4. Delta服务 (可选择标准或小波包)
        if self.use_delta_service:
            # 这里暂时保留原有逻辑，后续需要适配BrainWaveResult
            logger.info("Delta服务将在连接时初始化")
        
        # 5. Theta优化服务
        if self.enable_theta_optimization:
            self.theta_service = ThetaService(history_size=20, sampling_rate=512.0)
            logger.info("Theta优化服务已启用")
        else:
            self.theta_service = None
        
        # 6. 高级信号滤波器（集成冷启动改进功能）
        if self.enable_advanced_filter:
            self.advanced_filter = AdvancedSignalFilter(
                sampling_rate=512.0,
                window_size=20
            )
            logger.info("高级信号滤波器已启用（集成冷启动改进功能）")
        else:
            self.advanced_filter = None
            
        # 7. 频段优化服务
        if self.enable_band_optimization:
            self.frequency_band_service = FrequencyBandService(
                history_size=10, 
                outlier_threshold=2.5
            )
            logger.info("频段优化服务已启用")
        else:
            self.frequency_band_service = None
    
    def connect_device(self, max_retries=3):
        """连接设备"""
        for attempt in range(max_retries):
            try:
                logger.info(f"尝试连接设备 (第{attempt + 1}次): {self.port}")
                
                if self.use_delta_service:
                    # 使用小波包DeltaService，传递分析时长参数
                    self.neuropy = WaveletDeltaService(self.port, analysis_duration=self.analysis_duration)
                    logger.info(f"使用小波包DeltaService连接设备: {self.port}, 分析时长: {self.analysis_duration}秒")
                else:
                    self.neuropy = NeuroPy(self.port)
                    logger.info(f"使用标准NeuroPy连接设备: {self.port}")
                
                # 设置rawValue回调函数
                self.neuropy.setCallBack("rawValue", self._on_raw_value_callback)
                logger.info("rawValue回调函数已设置")
                
                # 启动数据采集
                self.neuropy.start()
                logger.info(f"设备连接成功: {self.port}")
                
                # 等待连接稳定
                time.sleep(2)
                return True
                
            except Exception as e:
                device_error = DeviceConnectionException(
                    f"设备连接失败 (第{attempt + 1}次): {str(e)}", 
                    port=self.port
                )
                global_exception_handler.handle_exception(device_error)
                
                if self.neuropy:
                    try:
                        self.neuropy.stop()
                    except:
                        pass
                    self.neuropy = None
                
                if attempt < max_retries - 1:
                    logger.info("等待2秒后重试...")
                    time.sleep(2)
                else:
                    exception = DeviceConnectionException(f"设备连接失败，已尝试{max_retries}次，端口: {self.port}")
                    global_exception_handler.handle_exception(exception)
                    raise exception
        
        return False
    
    def get_brain_wave_data(self):
        """
        获取经过完整处理流程的脑电数据
        
        处理流程:
        1. 获取原始数据
        2. 陷波滤波器 (去除50Hz工频干扰)
        3. EOG伪迹去除 (如果启用)
        4. EMG伪迹去除 (如果启用)
        5. Delta服务处理 (如果启用)
        6. Theta优化 (如果启用)
        7. 高级信号滤波 (如果启用)
        8. 频段优化 (如果启用)
        
        Returns:
            BrainWaveResult: 处理后的脑电数据，如果失败返回None
        """
        try:
            if not self.neuropy:
                exception = DeviceConnectionException("设备未连接，无法获取脑电数据")
                global_exception_handler.handle_exception(exception)
                raise exception
            
            # 步骤1: 获取原始数据
            result = self._get_raw_data()
            if not result:
                return None
            
            # 记录原始数据到logs文件夹
            self._log_raw_data_to_file(result)
            
            # 步骤2: 陷波滤波器 (去除50Hz工频干扰)
            if self.enable_notch_filter and self.notch_filter:
                self._log_step_start("步骤2", "陷波滤波器(50Hz)", result)
                result = self._apply_notch_filter(result)
                self._log_step_end("步骤2", "陷波滤波器(50Hz)", result)
            
            # 步骤3: EOG伪迹去除 (如果启用)
            if self.enable_eog_removal and self.eog_remover:
                self._log_step_start("步骤3", "EOG眼动伪迹去除", result)
                result = self._apply_eog_removal(result)
                self._log_step_end("步骤3", "EOG眼动伪迹去除", result)
            
            # 步骤4: EMG伪迹去除 (如果启用)
            if self.enable_emg_removal and self.emg_remover:
                self._log_step_start("步骤4", "EMG肌电伪迹去除", result)
                result = self._apply_emg_removal(result)
                self._log_step_end("步骤4", "EMG肌电伪迹去除", result)
            
            # 步骤5: Delta服务处理 (如果启用)
            if self.use_delta_service:
                self._log_step_start("步骤5", "Delta小波包处理", result)
                result = self._apply_delta_service(result)
                self._log_step_end("步骤5", "Delta小波包处理", result)
            
            # 步骤6: Theta优化 (如果启用)
            if self.enable_theta_optimization and self.theta_service:
                self._log_step_start("步骤6", "Theta波段优化", result)
                result = self._apply_theta_optimization(result)
                self._log_step_end("步骤6", "Theta波段优化", result)
            
            # 步骤7: 高级信号滤波 (如果启用)
            if self.enable_advanced_filter and self.advanced_filter:
                self._log_step_start("步骤7", "高级信号滤波", result)
                result = self._apply_advanced_filter(result)
                self._log_step_end("步骤7", "高级信号滤波", result)
            
            # 步骤8: 频段优化 (如果启用)
            if self.enable_band_optimization and self.frequency_band_service:
                self._log_step_start("步骤8", "频段优化", result)
                result = self._apply_band_optimization(result)
                self._log_step_end("步骤8", "频段优化", result)
            
            return result
                
        except Exception as e:
            data_error = DeviceDataException(
                f"获取脑电数据失败: {str(e)}",
                data_type="brain_wave_data"
            )
            global_exception_handler.handle_exception(data_error)
            return None
    
    def get_brain_wave_data_from_input(self, input_result):
        """
        对外部输入的BrainWaveResult数据进行完整处理流程
        
        Args:
            input_result: BrainWaveResult对象，包含原始脑波数据
            
        Returns:
            BrainWaveResult: 处理后的脑电数据，如果失败返回None
        """
        try:
            if not input_result:
                exception = DeviceDataException("输入数据为空，无法进行脑电数据处理")
                global_exception_handler.handle_exception(exception)
                raise exception
            
            result = input_result
            
            # 记录输入的原始数据
            self._log_raw_data_to_file(result)
            
            # 步骤2: 陷波滤波器 (去除50Hz工频干扰)
            if self.enable_notch_filter and self.notch_filter:
                self._log_step_start("步骤2", "陷波滤波器(50Hz)", result)
                result = self._apply_notch_filter(result)
                self._log_step_end("步骤2", "陷波滤波器(50Hz)", result)
            
            # 步骤3: EOG伪迹去除 (如果启用)
            if self.enable_eog_removal and self.eog_remover:
                self._log_step_start("步骤3", "EOG眼动伪迹去除", result)
                result = self._apply_eog_removal(result)
                self._log_step_end("步骤3", "EOG眼动伪迹去除", result)
            
            # 步骤4: EMG伪迹去除 (如果启用)
            if self.enable_emg_removal and self.emg_remover:
                self._log_step_start("步骤4", "EMG肌电伪迹去除", result)
                result = self._apply_emg_removal(result)
                self._log_step_end("步骤4", "EMG肌电伪迹去除", result)
            
            # 步骤5: Delta服务处理 (如果启用)
            if self.use_delta_service:
                self._log_step_start("步骤5", "Delta小波包处理", result)
                result = self._apply_delta_service(result)
                self._log_step_end("步骤5", "Delta小波包处理", result)
            
            # 步骤6: Theta优化 (如果启用)
            if self.enable_theta_optimization and self.theta_service:
                self._log_step_start("步骤6", "Theta波段优化", result)
                result = self._apply_theta_optimization(result)
                self._log_step_end("步骤6", "Theta波段优化", result)
            
            # 步骤7: 高级信号滤波 (如果启用)
            if self.enable_advanced_filter and self.advanced_filter:
                self._log_step_start("步骤7", "高级信号滤波", result)
                result = self._apply_advanced_filter(result)
                self._log_step_end("步骤7", "高级信号滤波", result)
            
            # 步骤8: 频段优化 (如果启用)
            if self.enable_band_optimization and self.frequency_band_service:
                self._log_step_start("步骤8", "频段优化", result)
                result = self._apply_band_optimization(result)
                self._log_step_end("步骤8", "频段优化", result)
            
            return result
                
        except Exception as e:
            processing_error = SignalProcessingException(
                f"处理输入脑电数据失败: {str(e)}",
                processing_step="input_data_processing"
            )
            global_exception_handler.handle_exception(processing_error)
            return None
    
    def _get_raw_data(self):
        """步骤1: 获取原始数据并转换为BrainWaveResult (支持8频域)"""
        try:
            # 获取当前原始信号值并添加到缓冲区
            current_raw_value = self.neuropy.rawValue
            self.raw_signal_buffer.append(current_raw_value)
            
            # 创建8频域BrainWaveResult，直接从NeuroPy获取8个频域值
            # 注意：这些频段值将在陷波滤波后被重新计算的值替换
            result = BrainWaveResult.from_neuropy(self.neuropy)
            
            result.add_processing_step("raw_data_8bands", {
                "source": "neuropy",
                "frequency_bands": 8,
                "raw_buffer_size": len(self.raw_signal_buffer),
                "current_raw_value": current_raw_value,
                "band_values": {
                    "delta": result.delta,
                    "theta": result.theta,
                    "low_alpha": result.low_alpha,
                    "high_alpha": result.high_alpha,
                    "low_beta": result.low_beta,
                    "high_beta": result.high_beta,
                    "low_gamma": result.low_gamma,
                    "mid_gamma": result.mid_gamma
                }
            })
            return result
        except Exception as e:
            data_error = DeviceDataException(
                f"获取8频域原始数据失败: {e}",
                data_type="raw_data_8bands"
            )
            global_exception_handler.handle_exception(data_error)
            return None

    def _apply_notch_filter(self, result):
        """步骤2: 应用陷波滤波器"""
        try:
            if not self.enable_notch_filter:
                logger.info("[DEBUG] 陷波滤波器未启用")
                return result
            
            # DEBUG: 添加调试信息
            logger.info(f"[DEBUG] WaveService: 开始应用陷波滤波器")
            logger.info(f"[DEBUG] WaveService: raw_signal_buffer长度: {len(self.raw_signal_buffer)}")
            if len(self.raw_signal_buffer) > 0:
                logger.info(f"[DEBUG] WaveService: raw_signal_buffer最新5个值: {list(self.raw_signal_buffer)[-5:]}")
            logger.info(f"[DEBUG] WaveService: 当前rawValue: {result.rawValue}")
                
            # 传递原始时域信号缓冲区给陷波滤波器
            # 陷波滤波器将对时域信号进行滤波，然后重新计算频段功率
            filtered_result = self.notch_filter.filter_brain_wave_result(result, list(self.raw_signal_buffer))
            
            logger.info(f"[DEBUG] WaveService: 陷波滤波完成")
            
            # 添加处理步骤信息
            filtered_result.add_processing_step("notch_filter", {
                "filter_type": "50Hz_notch",
                "raw_buffer_used": len(self.raw_signal_buffer),
                "recalculated_bands": True
            })
            
            return filtered_result
        except Exception as e:
            logger.error(f"[DEBUG] WaveService: 陷波滤波异常: {e}")
            filter_error = FilterException(
                f"陷波滤波失败: {e}",
                filter_type="notch_filter"
            )
            global_exception_handler.handle_exception(filter_error)
            return result

    def _apply_eog_removal(self, result):
        """步骤3: 应用EOG伪迹去除"""
        try:
            if not self.enable_eog_removal:
                logger.info("EOG伪迹去除已禁用，跳过处理")
                return result
            
            # 添加眨眼强度信息
            blink_strength = 0
            if hasattr(self.neuropy, 'blinkStrength'):
                # 从NeuroPy设备获取眨眼强度
                blink_strength = self.neuropy.blinkStrength
            else:
                # 对于外部输入数据，基于delta波段变化计算眨眼强度
                if hasattr(self.eog_remover, 'signal_buffer') and len(self.eog_remover.signal_buffer['delta']) >= 3:
                    delta_values = list(self.eog_remover.signal_buffer['delta'])
                    recent_delta = result.delta
                    avg_delta = sum(delta_values[-3:]) / 3 if len(delta_values) >= 3 else delta_values[-1] if delta_values else recent_delta
                    blink_strength = abs(recent_delta - avg_delta) * 0.001  # 缩放因子调整
                else:
                    # 使用当前delta值作为基础眨眼强度
                    blink_strength = result.delta * 0.0005  # 基础缩放因子
            
            # 确保processing_info存在并设置blink_strength
            if 'processing_info' not in result.__dict__:
                result.processing_info = {}
            result.processing_info['blink_strength'] = blink_strength
            logger.info(f"【WaveService】眨眼强度: {blink_strength:.2f}")
            
            # 应用EOG伪迹去除
            logger.info(f"【WaveService】开始EOG伪迹去除处理...")
            processed_result = self.eog_remover.process_signal(result)
            
            # 检查处理结果
            if processed_result != result:
                logger.info(f"【WaveService】EOG伪迹去除成功完成")
            else:
                logger.info(f"【WaveService】EOG伪迹去除未改变信号")
                
            return processed_result
        except Exception as e:
            filter_error = FilterException(
                f"EOG伪迹去除失败: {e}",
                filter_type="eog_removal"
            )
            global_exception_handler.handle_exception(filter_error)
            return result

    def _apply_emg_removal(self, result):
        """步骤4: 应用EMG伪迹去除"""
        try:
            if not self.enable_emg_removal:
                logger.info("EMG伪迹去除已禁用，跳过处理")
                return result
            
            # 应用EMG伪迹去除
            logger.info(f"【WaveService】开始EMG伪迹去除处理...")
            processed_result = self.emg_remover.process_signal(result)
            
            # 检查处理结果
            if processed_result != result:
                logger.info(f"【WaveService】EMG伪迹去除成功完成")
            else:
                logger.info(f"【WaveService】EMG伪迹去除未改变信号")
                
            return processed_result
        except Exception as e:
            filter_error = FilterException(
                f"EMG伪迹去除失败: {e}",
                filter_type="emg_removal"
            )
            global_exception_handler.handle_exception(filter_error)
            return result

    def _apply_delta_service(self, result):
        """步骤5: 应用Delta服务 (如果使用WaveletDeltaService)"""
        try:
            if not self.use_delta_service:
                return result
                
            # 使用新的process_delta_result方法
            if hasattr(self.neuropy, 'process_delta_result'):
                return self.neuropy.process_delta_result(result)
            
            # 兼容旧版接口
            if hasattr(self.neuropy, 'filtered_delta'):
                original_delta = result.delta
                filtered_delta = self.neuropy.filtered_delta
                
                result.update_band('delta', filtered_delta, "WaveletDelta过滤")
                result.add_processing_step("delta_service", {
                    "service_type": "WaveletDeltaService",
                    "original_delta": original_delta,
                    "filtered_delta": filtered_delta
                })
            
            return result
        except Exception as e:
            processing_error = SignalProcessingException(
                f"Delta服务处理失败: {e}",
                signal_type="delta_service"
            )
            global_exception_handler.handle_exception(processing_error)
            return result
    
    def _apply_theta_optimization(self, result):
        """步骤6: 应用Theta优化"""
        try:
            # 直接传入BrainWaveResult对象
            optimized_result = self.theta_service.process_theta(result)
            
            return optimized_result
        except Exception as e:
            processing_error = SignalProcessingException(
                f"Theta优化失败: {e}",
                signal_type="theta_optimization"
            )
            global_exception_handler.handle_exception(processing_error)
            return result

    def _apply_advanced_filter(self, result):
        """步骤7: 应用高级信号滤波"""
        try:
            # 直接传入BrainWaveResult对象
            filtered_dict = self.advanced_filter.process_multi_band_signal(result)
            
            # 检查返回类型并转换
            if isinstance(filtered_dict, dict):
                # 从字典创建BrainWaveResult对象
                from response.BrainWaveResult import BrainWaveResult
                filtered_result = BrainWaveResult.from_dict(filtered_dict)
            else:
                # 如果返回的是BrainWaveResult对象，直接使用
                filtered_result = filtered_dict
            
            # 添加处理步骤信息
            filtered_result.add_processing_step("advanced_signal_filter", {
                "original_theta": result.theta,
                "original_alpha": result.alpha,
                "original_beta": result.beta,
                "original_gamma": result.gamma,
                "filtered_theta": filtered_result.theta,
                "filtered_alpha": filtered_result.alpha,
                "filtered_beta": filtered_result.beta,
                "filtered_gamma": filtered_result.gamma
            })
            
            return filtered_result
        except Exception as e:
            filter_error = FilterException(
                f"高级信号滤波失败: {e}",
                filter_type="advanced_signal_filter"
            )
            global_exception_handler.handle_exception(filter_error)
            return result

    def _apply_band_optimization(self, result):
        """步骤8: 应用频段优化"""
        try:
            # 直接传入BrainWaveResult对象
            optimized_result = self.frequency_band_service.process_frequency_bands(result)
            
            return optimized_result
        except Exception as e:
            processing_error = SignalProcessingException(
                f"频段优化失败: {e}",
                signal_type="band_optimization"
            )
            global_exception_handler.handle_exception(processing_error)
            return result

    def _log_step_start(self, step_name, filter_name, result):
        """记录处理步骤开始前的数据"""
        try:
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
            log_content = f"{timestamp}：{step_name}：{filter_name}。处理前数据 - Delta: {result.delta:.2f}μV², Theta: {result.theta:.2f}μV², Alpha: {result.alpha:.2f}μV², Beta: {result.beta:.2f}μV², Gamma: {result.gamma:.2f}μV²\n"
            
            # 确保logs目录存在
            logs_dir = os.path.join(os.getcwd(), "logs")
            if not os.path.exists(logs_dir):
                os.makedirs(logs_dir)
            
            # 生成日志文件名
            log_filename = f"brain_wave_processing_{datetime.now().strftime('%Y%m%d')}.log"
            log_filepath = os.path.join(logs_dir, log_filename)
            
            # 写入日志文件
            with open(log_filepath, 'a', encoding='utf-8') as f:
                f.write(log_content)
                
        except Exception as e:
             self.logger.warning(f"记录步骤开始日志失败: {e}")
    
    def _log_step_end(self, step_name, filter_name, result):
        """记录处理步骤结束后的数据"""
        try:
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
            log_content = f"{timestamp}：{step_name}：{filter_name}。处理后数据 - Delta: {result.delta:.2f}μV², Theta: {result.theta:.2f}μV², Alpha: {result.alpha:.2f}μV², Beta: {result.beta:.2f}μV², Gamma: {result.gamma:.2f}μV²\n\n"
            
            # 确保logs目录存在
            logs_dir = os.path.join(os.getcwd(), "logs")
            if not os.path.exists(logs_dir):
                os.makedirs(logs_dir)
            
            # 生成日志文件名
            log_filename = f"brain_wave_processing_{datetime.now().strftime('%Y%m%d')}.log"
            log_filepath = os.path.join(logs_dir, log_filename)
            
            # 写入日志文件
            with open(log_filepath, 'a', encoding='utf-8') as f:
                f.write(log_content)
                
        except Exception as e:
             self.logger.warning(f"记录步骤结束日志失败: {e}")

    def get_optimization_summary(self):
        """获取优化处理摘要"""
        try:
            result = self.get_brain_wave_data()
            if not result:
                return None
            
            # 获取处理步骤信息
            processing_steps = result.processing_info.get('processing_steps', []) if hasattr(result, 'processing_info') else []
            
            # 返回处理步骤摘要
            return {
                'processing_steps': processing_steps,
                'current_values': result.to_dict(),
                'enabled_filters': {
                    'notch_filter': self.enable_notch_filter,
                    'eog_removal': self.enable_eog_removal,
                    'emg_removal': self.enable_emg_removal,
                    'delta_service': self.use_delta_service,
                    'theta_optimization': self.enable_theta_optimization,
                    'advanced_filter': self.enable_advanced_filter,
                    'band_optimization': self.enable_band_optimization
                }
            }
            
        except Exception as e:
            exception = SignalProcessingException(f"获取优化摘要失败: {str(e)}")
            global_exception_handler.handle_exception(exception)
            raise exception

    def reset_optimization_history(self):
        """重置优化历史数据"""
        try:
            if self.theta_service:
                self.theta_service.reset_history()
            if self.advanced_filter:
                self.advanced_filter.reset_filter()
            if self.frequency_band_service:
                self.frequency_band_service.reset_history()
            if self.eog_remover:
                self.eog_remover.reset_statistics()
            if self.emg_remover:
                self.emg_remover.reset_statistics()
            logger.info("优化历史数据已重置")
        except Exception as e:
            exception = SignalProcessingException(f"重置优化历史失败: {str(e)}")
            global_exception_handler.handle_exception(exception)
            raise exception

    def get_eog_statistics(self):
        """获取EOG处理统计信息"""
        try:
            if self.enable_eog_removal and self.eog_remover:
                return self.eog_remover.get_statistics()
            return None
        except Exception as e:
            exception = SignalProcessingException(f"获取EOG统计信息失败: {str(e)}")
            global_exception_handler.handle_exception(exception)
            raise exception

    def get_emg_statistics(self):
        """获取EMG处理统计信息"""
        try:
            if self.enable_emg_removal and self.emg_remover:
                return self.emg_remover.get_statistics()
            return None
        except Exception as e:
            exception = SignalProcessingException(f"获取EMG统计信息失败: {str(e)}")
            global_exception_handler.handle_exception(exception)
            raise exception
            return None

    def _on_raw_value_callback(self, raw_value):
        """rawValue回调函数，用于512Hz数据采集"""
        try:
            # 将原始值添加到缓冲区
            self.raw_signal_buffer.append(raw_value)
            logger.debug(f"rawValue回调: {raw_value}, 缓冲区大小: {len(self.raw_signal_buffer)}")
        except Exception as e:
            logger.error(f"rawValue回调处理错误: {e}")
    
    def get_raw_data_dict(self):
        """获取原始数据字典格式 (兼容旧接口)
        
        Returns:
            dict: 原始脑电数据字典
        """
        try:
            result = self.get_brain_wave_data()
            if result:
                return result.to_dict()
            return None
        except Exception as e:
            exception = SignalProcessingException(f"获取原始数据字典失败: {str(e)}")
            global_exception_handler.handle_exception(exception)
            raise exception

    def _log_raw_data_to_file(self, result):
        """记录8频域原始数据到日志文件"""
        try:
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
            log_content = f"{timestamp}：步骤1：获取8频域原始数据。原始数据 - Delta: {result.delta:.2f}μV², Theta: {result.theta:.2f}μV², Low Alpha: {result.low_alpha:.2f}μV², High Alpha: {result.high_alpha:.2f}μV², Low Beta: {result.low_beta:.2f}μV², High Beta: {result.high_beta:.2f}μV², Low Gamma: {result.low_gamma:.2f}μV², Mid Gamma: {result.mid_gamma:.2f}μV², [合成] Alpha: {result.alpha:.2f}μV², Beta: {result.beta:.2f}μV², Gamma: {result.gamma:.2f}μV², RawValue: {result.rawValue}, Attention: {result.attention}, Meditation: {result.meditation}\n\n"
            
            # 确保logs目录存在
            logs_dir = os.path.join(os.getcwd(), "logs")
            if not os.path.exists(logs_dir):
                os.makedirs(logs_dir)
            
            # 生成日志文件名
            log_filename = f"brain_wave_processing_{datetime.now().strftime('%Y%m%d')}.log"
            log_filepath = os.path.join(logs_dir, log_filename)
            
            # 写入日志文件
            with open(log_filepath, 'a', encoding='utf-8') as f:
                f.write(log_content)
                
        except Exception as e:
             self.logger.warning(f"记录原始数据日志失败: {e}")

    def _output_scientific_analysis(self, data_buffer, start_time):
        """输出科学分析结果"""
        try:
            if len(data_buffer) < 5:  # 降低最小样本数要求
                return
            
            # 获取最新的处理结果
            latest_result = self.get_brain_wave_data()
            if not latest_result:
                return
            
            # 确保latest_result是BrainWaveResult对象
            latest_result_dict = latest_result.to_dict() if hasattr(latest_result, 'to_dict') else {}
            
            elapsed_time = time.time() - start_time
            logger.info(f"=== 科学分析报告 (运行时间: {elapsed_time:.1f}秒) ===")
            logger.info(f"数据样本数: {len(data_buffer)}")
            logger.info(f"当前脑电状态: {latest_result_dict}")
            
            # 输出处理步骤
            if hasattr(latest_result, 'processing_info') and 'processing_steps' in latest_result.processing_info:
                logger.info("数据处理步骤:")
                for step in latest_result.processing_info['processing_steps']:
                    if isinstance(step, dict):
                        logger.info(f"  - {step.get('step', '未知步骤')}: {step.get('details', {}).get('description', '无描述')}")
            
        except Exception as e:
            exception = SignalProcessingException(f"科学分析输出失败: {str(e)}")
            global_exception_handler.handle_exception(exception)
            raise exception

    def disconnect_device(self):
        """断开设备连接"""
        try:
            if self.neuropy:
                logger.info("正在断开设备连接...")
                # 确保停止数据收集（如果是DeltaService）
                if hasattr(self.neuropy, 'stop_collection'):
                    try:
                        self.neuropy.stop_collection()
                        logger.info("数据收集已停止")
                    except Exception as e:
                        logger.warning(f"停止数据收集时出现警告: {str(e)}")
                
                # 停止设备连接
                self.neuropy.stop()
                logger.info("设备连接已断开")
                
                # 等待一小段时间确保资源完全释放
                time.sleep(0.5)
                
                self.neuropy = None
                logger.info("设备对象已清理")
        except Exception as e:
            exception = DeviceConnectionException(f"断开设备连接失败: {str(e)}")
            global_exception_handler.handle_exception(exception)
            # 强制清理对象引用
            self.neuropy = None
            # 额外等待时间确保串口资源释放
            time.sleep(1.0)
            logger.info("已强制清理设备对象")
            raise exception


# 使用示例
if __name__ == "__main__":
    import time
    
    # 创建集成了所有功能的服务
    service = WaveService(
        enable_notch_filter=True,     # 启用陷波滤波器
        enable_eog_removal=False,     # 禁用EOG伪迹去除 - 验证EOG是否启动
        enable_emg_removal=False,     # 禁用EMG伪迹去除 - 验证EMG是否启动
        use_delta_service=False,       # 使用Delta服务
        enable_theta_optimization=False, # 启用Theta优化
        enable_advanced_filter=False,  # 启用高级信号滤波
        enable_band_optimization=False # 启用频段优化
    )
    print("NeuroSky 脑电数据采集程序 - 集成版本")
    # print("数据处理流程：原始数据 -> 陷波滤波 -> EOG伪迹去除 -> Delta处理 -> Theta优化 -> 高级滤波 -> 频段优化")  # 删除流程打印
    print("正在连接设备...")
    
    if service.connect_device():
        print("设备连接成功！")
        print("等待设备稳定...")
        time.sleep(3)  # 等待设备稳定
        
        print("开始数据收集，每{}秒输出一次批量数据...".format(service.analysis_duration))
        print("频段优化功能已启用，将自动过滤异常值并平滑数据")
        print("按 Ctrl+C 停止程序")
        
        try:
            # 启动数据收集
            if hasattr(service.neuropy, 'start_collection'):
                service.neuropy.start_collection()
                logger.info("数据收集已启动")
            else:
                # print("警告：DeltaService不支持批量收集模式")  # 删除警告打印
                pass
            
            # 科学分析数据收集
            scientific_data_buffer = []
            collection_start_time = time.time()
            collection_interval = service.analysis_duration  # 使用动态分析时长
            
            # 保持程序运行，收集和分析科学数据
            loop_count = 0
            while True:
                time.sleep(1)  # 主线程休眠
                loop_count += 1
                
                # 每秒收集一次科学分析数据
                try:
                    brain_data = service.get_brain_wave_data()
                    if brain_data:
                        current_time = time.time()
                        # 将BrainWaveResult对象转换为字典
                        brain_data_dict = brain_data.to_dict() if hasattr(brain_data, 'to_dict') else {}
                        
                        # 添加到科学数据缓冲区
                        scientific_data_buffer.append({
                            'timestamp': current_time,
                            'brain_data': brain_data_dict
                        })
                        
                        # 每N秒输出一次科学分析报告（N为动态设置的分析时长）
                        if current_time - collection_start_time >= collection_interval:
                            service._output_scientific_analysis(scientific_data_buffer, collection_start_time)
                            scientific_data_buffer.clear()
                            collection_start_time = current_time
                            
                except Exception as e:
                    exception = SignalProcessingException(f"科学数据收集出错: {str(e)}")
                    global_exception_handler.handle_exception(exception)
                    # 继续运行，不中断数据收集
                
                # 每30秒输出优化摘要
                if loop_count % 30 == 0:
                    try:
                        summary = service.get_optimization_summary()
                        if summary:
                            logger.info(f"\n=== 优化摘要 (第{loop_count//30}次) ===")
                            # 获取当前值
                            current_values = summary.get('current_values', {})
                            
                            # 获取启用的过滤器
                            enabled_filters = summary.get('enabled_filters', {})
                            logger.info(f"启用的过滤器: {', '.join([k for k, v in enabled_filters.items() if v])}")
                            
                            # 获取EOG统计信息
                            if enabled_filters.get('eog_removal', False):
                                eog_stats = service.get_eog_statistics()
                                if eog_stats:
                                    pass
                            
                            logger.info("=" * 40)
                        
                        # 检查设备是否还在正常工作
                        if hasattr(service.neuropy, 'neuropy') and service.neuropy.neuropy:
                            if not service.neuropy.neuropy.threadRun:
                                logger.warning("检测到设备连接中断，尝试重新连接...")
                                service.disconnect_device()
                                if not service.connect_device():
                                    exception = DeviceConnectionException("重新连接失败，程序退出")
                                    global_exception_handler.handle_exception(exception)
                                    break
                                if hasattr(service.neuropy, 'start_collection'):
                                    service.neuropy.start_collection()
                    except Exception as e:
                        exception = SignalProcessingException(f"状态检查出错: {str(e)}")
                        global_exception_handler.handle_exception(exception)
                        # 继续运行，不中断程序
                
        except KeyboardInterrupt:
            logger.info("\n正在停止...")
            # 停止数据收集并输出最后的数据
            if hasattr(service.neuropy, 'stop_collection'):
                service.neuropy.stop_collection()
        except Exception as e:
            exception = SignalProcessingException(f"程序运行出错: {str(e)}")
            global_exception_handler.handle_exception(exception)
        finally:
            service.disconnect_device()
    else:
        exception = DeviceConnectionException("设备连接失败")
        global_exception_handler.handle_exception(exception)